#pragma once

#include <string>
#include <unordered_set>
#include <vector>
#include <memory>
#include <mutex>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <algorithm>

namespace viml {

/**
 * 简化的内存优化器
 */
class MemoryOptimizer {
public:
    // 简化的统计信息
    struct SimpleStats {
        size_t total_objects = 0;
        size_t total_bytes = 0;
        size_t active_objects = 0;
        size_t cache_hits = 0;
        size_t cache_misses = 0;
        double hit_rate = 0.0;

        void clear() {
            total_objects = 0;
            total_bytes = 0;
            active_objects = 0;
            cache_hits = 0;
            cache_misses = 0;
            hit_rate = 0.0;
        }
    };

private:
    // 简单的对象池
    std::unordered_set<std::string> interned_strings_;
    mutable std::mutex mutex_;
    mutable SimpleStats stats_;

    static constexpr size_t MAX_POOL_SIZE = 1000;

public:
    MemoryOptimizer() {
        interned_strings_.reserve(100);
    }

    ~MemoryOptimizer() {
        clear();
    }

    // 字符串驻留
    const std::string* intern_string(const std::string& str) {
        if (str.empty()) {
            return nullptr;
        }

        std::lock_guard<std::mutex> lock(mutex_);

        auto it = interned_strings_.find(str);
        if (it != interned_strings_.end()) {
            ++stats_.cache_hits;
        } else {
            auto result = interned_strings_.insert(str);
            if (result.second) {
                ++stats_.total_objects;
                stats_.total_bytes += str.length();
                ++stats_.active_objects;
            }
            ++stats_.cache_misses;
        }

        // 更新命中率
        if (stats_.cache_hits + stats_.cache_misses > 0) {
            stats_.hit_rate = static_cast<double>(stats_.cache_hits) / (stats_.cache_hits + stats_.cache_misses);
        }

        return &(*it);
    }

    bool contains_string(const std::string& str) const {
        std::lock_guard<std::mutex> lock(mutex_);
        return interned_strings_.find(str) != interned_strings_.end();
    }

    SimpleStats get_stats() const {
        std::lock_guard<std::mutex> lock(mutex_);
        return stats_;
    }

    void reset_stats() {
        std::lock_guard<std::mutex> lock(mutex_);
        stats_.clear();
    }

    void clear() {
        std::lock_guard<std::mutex> lock(mutex_);

        interned_strings_.clear();
        stats_.clear();
    }

    void optimize_pool() {
        std::lock_guard<std::mutex> lock(mutex_);

        if (interned_strings_.size() > MAX_POOL_SIZE) {
            // 简单的清理策略：清理最旧的25%
            auto it = interned_strings_.begin();
            size_t count = 0;
            while (it != interned_strings_.end() && count < interned_strings_.size() / 4) {
                interned_strings_.erase(*it);
                ++count;
                ++it;
            }
        }
    }

    void print_stats() const {
        auto stats = get_stats();

        std::cout << "=== 简化内存优化器统计 ===" << std::endl;
        std::cout << "总对象数: " << stats.total_objects << std::endl;
        std::cout << "总字节数: " << stats.total_bytes << std::endl;
        std::cout << "活跃对象数: " << stats.active_objects << std::endl;
        std::cout << "缓存命中: " << stats.cache_hits << std::endl;
        std::cout << "缓存未命中: " << stats.cache_misses << std::endl;
        std::cout << "命中率: " << std::fixed << std::setprecision(2)
                  << (stats.hit_rate * 100) << "%" << std::endl;
        std::cout << "字符串池大小: " << interned_strings_.size() << std::endl;
        std::cout << "=================" << std::endl;
    }

    std::string generate_report() const {
        auto stats = get_stats();

        std::ostringstream report;
        report << "=== 简化内存优化报告 ===" << std::endl;
        report << "总对象数: " << stats.total_objects << std::endl;
        report << "命中率: " << std::fixed << std::setprecision(2)
               << (stats.hit_rate * 100) << "%" << std::endl;
        report << "字符串池效率: " << (stats.total_objects > 0 ?
               static_cast<double>(stats.total_bytes) / stats.total_objects : 0.0)
               << " 字节/对象" << std::endl;
        report << "=================" << std::endl;

        return report.str();
    }
};

/**
 * 全局内存优化器
 */
class GlobalMemoryOptimizer {
private:
    static std::unique_ptr<MemoryOptimizer> instance_;
    static std::mutex instance_mutex_;
    static bool initialized_;

public:
    static MemoryOptimizer& get_instance();
    static void initialize();
    static void shutdown();
    static bool is_initialized();
};

} // namespace viml